// customer_people.c
#include "customer_people.h"
#include "login.h" // 引入login.h以获取user变量
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static lv_obj_t *chat_area; // 聊天显示区域
static lv_obj_t *input_ta;  // 输入框
static lv_obj_t *send_btn;  // 发送按钮
static lv_obj_t *kb = NULL;

// 全局变量用于存储最后一条管理员消息
static char last_admin_message[256] = {0};

// 返回主界面
static void return_to_main_cb(lv_event_t *e) 
{
    lv_scr_load(customer_scr);
}

// 输入框回调
static void ta_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *ta = lv_event_get_target(e);

    if(code == LV_EVENT_FOCUSED) {
        lv_keyboard_set_textarea(kb, ta);   /* 关联键盘 */
        lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_move_foreground(kb);

        /* 把输入框底部贴到键盘顶部 */
        lv_coord_t kb_h = lv_obj_get_height(kb);
        lv_coord_t ta_h = lv_obj_get_height(ta);
        lv_obj_set_y(ta, LV_VER_RES - kb_h - ta_h);   /* 紧贴键盘上方 */
    }
    else if(code == LV_EVENT_DEFOCUSED) {
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);      /* 失焦隐藏键盘 */
    }
}

// 解析JSON文件并检查是否有管理员消息
// 解析JSON文件并检查是否有管理员消息
static void check_admin_message(void)
{
    // 读取speak.json文件
    FILE *file = fopen("speak.json", "r");
    if (!file) {
        perror("无法打开speak.json");
        return;
    }

    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    if (length <= 0) {
        fclose(file);
        return;
    }
    
    fseek(file, 0, SEEK_SET);
    
    char *data = (char *)malloc(length + 1);
    if (!data) {
        fclose(file);
        return;
    }
    
    size_t read = fread(data, 1, length, file);
    fclose(file);
    
    if (read != length) {
        printf("文件读取不完整: %zu/%ld 字节\n", read, length);
        free(data);
        return;
    }
    
    data[length] = '\0';
    
    // printf("读取的JSON内容: %s\n", data); 

    // 解析JSON
    cJSON *root = cJSON_Parse(data);
    free(data);
    
    if (!root) {
        printf("JSON解析失败: %s\n", cJSON_GetErrorPtr());
        return;
    }

    // 检查是否符合管理员消息条件
    cJSON *code = cJSON_GetObjectItemCaseSensitive(root, "code");
    cJSON *send = cJSON_GetObjectItemCaseSensitive(root, "send");
    cJSON *to = cJSON_GetObjectItemCaseSensitive(root, "to");
    cJSON *message = cJSON_GetObjectItemCaseSensitive(root, "message");

    if (cJSON_IsNumber(code) && code->valueint == 119 &&
        cJSON_IsString(send) && strcmp(send->valuestring, "admin") == 0 &&
        cJSON_IsString(to) && strcmp(to->valuestring, user) == 0 &&
        cJSON_IsString(message))
    {
        printf("检测到管理员消息: %s\n", message->valuestring); // 调试信息
        
        // 检查是否是新消息
        if (strcmp(message->valuestring, last_admin_message) != 0) 
        {
            strncpy(last_admin_message, message->valuestring, sizeof(last_admin_message) - 1);
            
            // 添加管理员消息到聊天区域
            lv_obj_t *admin_msg = lv_label_create(chat_area);
            lv_label_set_text_fmt(admin_msg, "管理员: %s", message->valuestring);
            lv_obj_set_style_text_align(admin_msg, LV_TEXT_ALIGN_LEFT, 0);
            lv_obj_set_style_text_color(admin_msg, lv_color_hex(0x28A745), 0);
            lv_obj_set_style_text_font(admin_msg, font_chinese, 0);
            lv_obj_set_width(admin_msg, LV_PCT(100));
            
            // 滚动到底部
            lv_obj_scroll_to_y(chat_area, lv_obj_get_scroll_bottom(chat_area), LV_ANIM_ON);
        }
    }
    
    cJSON_Delete(root);
}

// 定时器回调函数，定期检查新消息
static void check_message_timer_cb(lv_timer_t *timer)
{
    check_admin_message();
}

// 发送消息事件处理
// 发送消息事件处理
// 发送消息事件处理
static void send_msg_event_cb(lv_event_t *e) 
{
    // 首先获取输入框的文本
    const char *msg = lv_textarea_get_text(input_ta);
    // printf("调试: 输入框内容: '%s'\n", msg); // 添加调试信息
    
    if(strlen(msg) == 0) 
    {
        printf("调试: 输入框为空，不发送?消息\n");
        return;
    }
    
    // 添加用户消息到聊天区域
    lv_obj_t *user_msg = lv_label_create(chat_area);
    lv_label_set_text_fmt(user_msg, "您: %s", msg);
    lv_obj_set_style_text_align(user_msg, LV_TEXT_ALIGN_RIGHT, 0);
    lv_obj_set_style_text_color(user_msg, lv_color_hex(0x007ACC), 0);
    lv_obj_set_style_text_font(user_msg, font_chinese, 0);
    lv_obj_set_width(user_msg, LV_PCT(100));
    
    // 创建JSON对象
    cJSON *root = cJSON_CreateObject();
    if (!root) {
        printf("创建JSON对象失败\n");
        return;
    }
    
    cJSON_AddNumberToObject(root, "code", 120);
    cJSON_AddStringToObject(root, "send", user);
    cJSON_AddStringToObject(root, "to", "admin");
    cJSON_AddStringToObject(root, "message", msg);
    
    // 转换为字符串并写入文件
    char *json_str = cJSON_PrintUnformatted(root);
    if (!json_str) {
        printf("JSON转换为字符串失败\n");
        cJSON_Delete(root);
        return;
    }
    
    // printf("准备写入JSON: %s\n", json_str);
    
    FILE *file = fopen("speak.json", "w");
    if (!file) {
        printf("无法打开文件 speak.json 进行写入\n");
        perror("错误信息");
        free(json_str);
        cJSON_Delete(root);
        return;
    }
    
    size_t written = fwrite(json_str, 1, strlen(json_str), file);
    if (written != strlen(json_str)) {
        printf("文件写入不完整: %zu/%zu 字节\n", written, strlen(json_str));
    } else {
        printf("成功写入 %zu 字节到 speak.json\n", written);
    }
    
    fclose(file);
    free(json_str);
    cJSON_Delete(root);
    
    // 现在才清空输入框
    lv_textarea_set_text(input_ta, "");
    // printf("调试: 已清空输入框\n");
    
    // 滚动到底部
    lv_obj_scroll_to_y(chat_area, lv_obj_get_scroll_bottom(chat_area), LV_ANIM_ON);
}

void people_scr_ui(void)
{
    // 创建标题
    lv_obj_t *title = lv_label_create(people_scr);
    lv_label_set_text(title, "人工客服");
    lv_obj_set_style_text_font(title, font_chinese, 0);
    lv_obj_set_style_text_color(title, lv_color_white(), 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 20);
    
    // 创建聊天区域
    chat_area = lv_obj_create(people_scr);
    lv_obj_set_size(chat_area, LV_PCT(90), LV_PCT(60));
    lv_obj_align(chat_area, LV_ALIGN_TOP_MID, 0, 60);
    lv_obj_set_style_bg_opa(chat_area, LV_OPA_50, 0);
    lv_obj_set_style_border_width(chat_area, 0, 0);
    lv_obj_set_flex_flow(chat_area, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(chat_area, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_pad_all(chat_area, 10, 0);
    
    // 创建输入区域
    lv_obj_t *input_cont = lv_obj_create(people_scr);
    lv_obj_set_size(input_cont, LV_PCT(90), LV_PCT(15));
    lv_obj_align(input_cont, LV_ALIGN_BOTTOM_MID, 0, -50);
    lv_obj_set_style_bg_opa(input_cont, LV_OPA_0, 0);
    lv_obj_set_style_border_width(input_cont, 0, 0);
    lv_obj_set_flex_flow(input_cont, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(input_cont, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    
    // 创建输入框
    input_ta = lv_textarea_create(input_cont);
    lv_obj_set_width(input_ta, LV_PCT(70));
    lv_obj_set_style_text_font(input_ta, font_chinese, 0);
    lv_textarea_set_placeholder_text(input_ta, "请输入您的问题...");
    lv_textarea_set_one_line(input_ta, true);
    // 添加事件回调，点击时显示键盘
    lv_obj_add_event_cb(input_ta, ta_event_cb, LV_EVENT_ALL, NULL);
    
    // 创建发送按钮
    send_btn = lv_btn_create(input_cont);
    lv_obj_set_size(send_btn, LV_PCT(20), 40);
    lv_obj_set_style_bg_color(send_btn, lv_color_hex(0x007ACC), 0);
    
    lv_obj_t *send_label = lv_label_create(send_btn);
    lv_label_set_text(send_label, "发送");
    lv_obj_set_style_text_font(send_label, font_chinese, 0);
    lv_obj_center(send_label);
    
    lv_obj_add_event_cb(send_btn, send_msg_event_cb, LV_EVENT_CLICKED, NULL);
    
    // 创建返回按钮
    lv_obj_t *people_back_btn = lv_btn_create(people_scr);
    lv_obj_set_size(people_back_btn, 100, 50);
    lv_obj_align(people_back_btn, LV_ALIGN_BOTTOM_LEFT, 20, -10);
    lv_obj_set_style_bg_color(people_back_btn, lv_color_hex(0x666666), 0);
    
    lv_obj_t *lable = lv_label_create(people_back_btn);
    lv_label_set_text(lable, "返回");
    lv_obj_set_style_text_font(lable, font_chinese, 0);
    lv_obj_center(lable);
    
    lv_obj_add_event_cb(people_back_btn, return_to_main_cb, LV_EVENT_CLICKED, NULL);
    
    // 创建键盘
    kb = lv_keyboard_create(people_scr);
    lv_obj_set_size(kb, LV_HOR_RES, LV_VER_RES / 2);
    lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
    lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    lv_obj_set_style_radius(kb, 10, 0);
    
    // 添加欢迎消息
    lv_obj_t *welcome_msg = lv_label_create(chat_area);
    lv_label_set_text(welcome_msg, "客服: 您好，我是人工客服，有什么可以帮助您的吗？");
    lv_obj_set_style_text_align(welcome_msg, LV_TEXT_ALIGN_LEFT, 0);
    lv_obj_set_style_text_color(welcome_msg, lv_color_hex(0x28A745), 0);
    lv_obj_set_style_text_font(welcome_msg, font_chinese, 0);
    lv_obj_set_width(welcome_msg, LV_PCT(100));
    
    // 创建定时器，定期检查新消息
    lv_timer_t *timer = lv_timer_create(check_message_timer_cb, 1000, NULL); // 每秒检查一次
    lv_timer_set_repeat_count(timer, -1); // 无限重复
    
    // 立即检查一次是否有未读消息
    check_admin_message();
}